const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
class MyPromise {
  constructor(executor) {
    executor(this.resolve, this.reject);
  }
  // promise状态
  status = PENDING;
  value = undefined;
  reason = undefined;
  // 用箭头函数以便于this指向实例对象
  // 成功回调
  successCB = undefined;
  // 失败回调
  failCB = undefined;
  resolve = (value) => {
    // 如果状态不是pending组织程序向下执行：实现只有等待的情况下状态可以更改
    if (this.status !== PENDING) return;
    // 将状态更改为成功
    this.status = FULFILLED;
    // 保存成功之后的值
    this.value = value;
    // 处理异步的情况，如果成功的回调存在就调用
    this.successCB && this.successCB(this.value);
  };

  // 保存失败之后的原因
  reject = (reason) => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    // 保存失败之后的原因
    this.reason = reason;
    // 处理异步的情况，如果失败的回调存在就调用
    this.failCB && this.failCB(this.reason);
  };

  then(successCB, failCB) {
    // 判断状态
    if (this.status === FULFILLED) {
      successCB(this.value);
    } else if (this.status === REJECTED) {
      failCB(this.reason);
    } else {
      // 等待
      this.successCB = successCB;
      this.failCB = failCB;
    }
  }
}
module.exports = MyPromise;
